var express = require('express');
var router = express.Router();
var moment = require('moment');
var async = require('async');
var officegen = require('officegen');

var db = require('./../../utils/db.js');

/**
 * 项目流程-需求 控制器
 */
router.get('/index', function (req, res, next) {
    res.render('process/requirement/index');
});

/**
 * 根据模块获取需求
 */
router.get('/listByModule', function (req, res, next) {
    var moduleId = req.query.moduleId;
    var sql = '';
    if (moduleId) {
        sql = "select *, (select version_number from version_base as v where v.id=p.version_id) as versionNumber, (SELECT loginname FROM base_user u WHERE u.id=p.create_by_id) AS create_by_name from project_progress_requirement p where module_id=" + moduleId + " order by create_time asc";
    } else {
        sql = "select *, (select version_number from version_base as v where v.id=p.version_id) as versionNumber, (SELECT loginname FROM base_user u WHERE u.id=p.create_by_id) AS create_by_name from project_progress_requirement p order by create_time asc";
    }
    db.query(sql, function (err, rows) {
        if (rows && rows.length >= 0) {
            for (var i = 0; i < rows.length; i++) {
                rows[i].create_time = moment(rows[i].create_time).format('YYYY-MM-DD HH:mm:ss');
            }
            res.json({
                errcode: 0,
                message: '根据模块获取需求成功',
                data: rows
            });

        } else {
            res.json({
                errcode: 1,
                message: '根据模块获取需求失败'
            });
        }

    });
});

/**
 * 添加
 */
router.get('/add', function (req, res, next) {
    var moduleId = req.query.moduleId;
    var projectId = req.session.projectId;
    if (moduleId) {
        var moduleSql = "select m.module_name from project_progress_module as m where m.id=" + moduleId;
        var versionSql = "select * from version_base as v where v.project_base_id=" + projectId;

        async.series([
            function (callback) {
                db.query(moduleSql, function (err, rows) {
                    callback(err, rows);
                });
            },
            function (callback) {
                db.query(versionSql, function (err, rows) {
                    callback(err, rows);
                });
            }
        ], function (err, values) {

            res.render('process/requirement/edit', {
                project: {
                    id: '',
                    projectId: req.session.project.id,
                    moduleId: moduleId,
                    moduleName: values[0][0].module_name,
                    requirementName: '',
                    detail: '',
                    level: 0,
                    versionId: '',
                    proposeUser: '',
                    useRole: ''
                },
                versionList: values[1]
            });
        });
    } else {
        var versionSql = "select * from version_base as v where v.project_base_id=" + projectId;
        db.query(versionSql, function (err, rows) {
            if (rows && rows.length > 0) {
                res.render('process/requirement/edit', {
                    project: {
                        id: '',
                        projectId: req.session.project.id,
                        moduleId: '',
                        moduleName: '',
                        requirementName: '',
                        detail: '',
                        level: 0,
                        versionId: '',
                        proposeUser: '',
                        useRole: ''
                    },
                    versionList: rows
                });
            }
        });

    }
});

/**
 * 编辑
 */
router.get('/edit/:id', function (req, res, next) {
    var id = req.params.id;
    var projectId = req.session.projectId;
    if (id) {
        var sql = "SELECT *,(select m.module_name from project_progress_module as m where m.id=r.module_id) as moduleName FROM project_progress_requirement as r WHERE r.id =" + id;
        var versionSql = "select * from version_base as v where v.project_base_id=" + projectId;

        async.series([
            function (callback) {
                db.query(sql, function (err, rows) {
                    callback(err, rows);
                });
            },
            function (callback) {
                db.query(versionSql, function (err, rows) {
                    callback(err, rows);
                });
            }
        ], function (err, values) {
            if (!err) {
                res.render('process/requirement/edit', {
                    project: {
                        id: values[0][0].id,
                        moduleId: values[0][0].module_id,
                        moduleName: values[0][0].moduleName,
                        requirementName: values[0][0].requirement_name,
                        detail: values[0][0].detail,
                        level: values[0][0].level,
                        versionId: values[0][0].version_id,
                        proposeUser: values[0][0].propose_user,
                        useRole: values[0][0].use_role
                    },
                    versionList: values[1]
                });
            } else {
                res.render('process/requirement/edit', {
                    project: {
                        id: '',
                        moduleId: '',
                        moduleName: '',
                        requirementName: '',
                        detail: '',
                        level: 0,
                        versionId: '',
                        proposeUser: '',
                        useRole: ''
                    }

                });
            }
        });
    }

});

/**
 * 保存
 */
router.post('/save', function (req, res, next) {
    var moduleId = req.body.moduleId ? req.body.moduleId.trim() : '';
    var requirementName = req.body.requirementName ? req.body.requirementName.trim() : '';
    var detail = req.body.detail ? req.body.detail.trim() : '';
    var level = req.body.level ? req.body.level.trim() : '';
    var versionId = req.body.versionId ? req.body.versionId.trim() : '';
    var proposeUser = req.body.proposeUser ? req.body.proposeUser.trim() : '';
    var useRole = req.body.useRole ? req.body.useRole.trim() : '';

    var projectId = req.session.projectId;
    var createTime = moment(new Date()).format('YYYY-MM-DD HH:mm:ss');
    var createById = req.session.loginedUser.id;

    var id = req.body.id;
    var sql = '';
    if (id) {
        sql = "update project_progress_requirement set module_id=" + moduleId + ",requirement_name='" + requirementName + "',detail='" + detail + "',level=" + level + ",version_id=" + versionId + ",propose_user='" + proposeUser + "',use_role='" + useRole + "' where id=" + id;
    } else {
        sql = "insert into project_progress_requirement(project_id, module_id,requirement_name,detail,level,version_id,propose_user,use_role,create_time,create_by_id,remark) values (" + projectId + "," + moduleId + ",'" + requirementName + "','" + detail + "'," + level + "," + versionId + ",'" + proposeUser + "','" + useRole + "','" + createTime + "'," + createById + ",'')";
    }

    db.query(sql, function (err, rows) {
        if (!err) {
            res.redirect("/process/requirement/index");
        } else {
            res.json({
                errcode: 1,
                message: '保存失败'
            });
        }
    });


});

/**
 * 删除
 */
router.post('/delete/:id', function (req, res, next) {
    var id = req.params.id;
    var sql = '';
    if (id) {
        sql = "delete from project_progress_requirement where id=" + id;
        db.query(sql, function (err, rows) {
            if (!err) {
                res.json({
                    errcode: 0,
                    message: '删除成功'
                });
            } else {
                res.json({
                    errcode: 1,
                    message: '删除失败'
                });
            }
        });
    } else {
        res.json({
            errcode: 2,
            message: '系统错误'
        });
    }


});

/**
 * 生成需求说明书 word
 */
router.get('/generateDoc', function (req, res, next) {
    var projectCode = req.session.project.project_code;     //todo 使用中文名称生成错误

    var moduleSql = "select * from project_progress_module order by code asc";
    db.query(moduleSql, function (err, rows) {
        if (rows && rows.length >= 0) {
            res.writeHead(200, {
                "Content-Type": "application/vnd.openxmlformats-officedocument.presentationml.presentation",
                'Content-disposition': 'attachment; filename=' + projectCode + '.docx'
            });

            var docx = officegen({
                'type': 'docx',
                'onend': function (written) {
                    console.log('Finish to create a PowerPoint file.\nTotal bytes created: ' + written + '\n');
                },
                'onerr': function (err) {
                    console.log(err);
                }
            });

            async.eachSeries(
                rows,
                function (item, callback) {
                    var module = item;
                    var pObj = docx.createListOfNumbers();
                    var fontSize = (22 - module.depth * 2 > 0) ? (22 - module.depth * 2) : 12;  //最大22，最小12
                    pObj.addText(module.module_name, {
                        bold: true,
                        font_size: fontSize
                    });

                    var requirementSql = "select *, (select version_number from version_base as v where v.id=p.version_id) as versionNumber, (SELECT loginname FROM base_user u WHERE u.id=p.create_by_id) AS create_by_name from project_progress_requirement p where module_id=" + module.id + " order by create_time asc";
                    db.query(requirementSql, function (err, rows) {
                        if (rows && rows.length > 0) {
                            for (var i = 0; i < rows.length; i++) {
                                var requiement = rows[i];
                                requiement.create_time = moment(requiement.create_time).format('YYYY-MM-DD HH:mm:ss');

                                var pObj = docx.createP();
                                pObj.addText(requiement.requirement_name);
                            }
                        }

                        callback(err, res);
                    })
                },
                function (err) {
                    if (err) {
                        console.log(err);
                    } else {
                        docx.generate(res);
                    }
                }
            );
        }


    });

});

function recusiveModule(module, docx) {
    if (module) {
        var pObj = docx.createP();
        pObj.addText(module.module_name);

        var moduleSql = "select * from project_progress_module where parent_id=" + module.id;
        db.query(moduleSql, function (err, rows) {
            if (err) {
                console.error(err);
            } else {
                if (rows.length > 0) {     //非叶子节点，继续深入
                    for (var i = 0; i < rows.length; i++) {
                        recusiveModule(rows[i], docx);
                    }
                } else {        //叶子节点，查询需求
                    var requirementSql = "select *, (select version_number from version_base as v where v.id=p.version_id) as versionNumber, (SELECT loginname FROM base_user u WHERE u.id=p.create_by_id) AS create_by_name from project_progress_requirement p where module_id=" + module.id + " order by create_time asc";
                    db.query(requirementSql, function (err, rows) {
                        if (rows && rows.length > 0) {
                            for (var i = 0; i < rows.length; i++) {
                                var requiement = rows[i];
                                requiement.create_time = moment(requiement.create_time).format('YYYY-MM-DD HH:mm:ss');

                                var pObj = docx.createP();
                                pObj.addText(requiement.requirement_name);
                            }
                        }
                    })
                }
            }

        });
    } else {
        return true;
    }

}

module.exports = router;
